//
//  PairChatWindowController.m
//  HiQ
//
//  Created by maxwell pang on 12-7-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "PairChatWindowController.h"
#import "Buddy.h"
#import "BuddyGroup.h"
#import "FileWindowController.h"
#import "MainWindowController.h"
#import "FileListenSocket.h"
#import "MsgHistoryWindowController.h"
#import "FileTransfer.h"
#import "FileEntity.h"
#import "FileAssistant.h"
#import "MacrosDefine.h" 

@interface PairChatWindowController ()

@end

@implementation PairChatWindowController

@synthesize isShow;
@synthesize peerBuddy;
@synthesize pairChat;
@synthesize chatMsg;
@synthesize sendMsg;

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        // Initialization code here.
        chatMessage = @"";
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        [[[MainWindowController sharedMainWindowController] pairChatArray] addObject:self];
        [nc addObserver:self selector:@selector(changeBackgroundImage:) name:ChangeBackgroundImageNotification object:nil];
    }
    
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)windowDidLoad
{
    [super windowDidLoad];
}

-(void) awakeFromNib
{
    [chatMsg setFont:[NSFont fontWithName:@"华文楷体" size:16]];
}

- (void)windowWillClose:(NSNotification *)notification
{
    //将聊天记录数据写入文件
    if (![chatMessage isEqualToString:@""]) {
        [FileAssistant saveData:chatMessage selfQQ:[NSString stringWithFormat:@"%li",selfInfo.buddyQQ] fileName:[NSString stringWithFormat:@"%li",peerBuddy.buddyQQ]];
    }

    [[[MainWindowController sharedMainWindowController] pairChatArray] removeObject:self];
}

- (void) initPairChat:(Buddy*)buddy selfBuddyInfo:(Buddy*)me 
{
    peerBuddy = buddy;
    selfInfo = me;
    pairChat = [[PairChat alloc] initWithQQ:buddy->buddyQQ ownQQ:selfInfo.buddyQQ];
    pairChat.delegate = self;
}

- (void) setNamePohtoAndBgImage:(NSString*)bgImageName
{
    [peerName setStringValue:peerBuddy->buddyName];
    [ownName setStringValue:selfInfo->buddyName];
    [peerPohto setImage:[NSImage imageNamed:peerBuddy.photo]];
    [peerPohto setImageScaling:NSScaleToFit];
    [ownPohto setImage:[NSImage imageNamed:selfInfo.photo]];
    [ownPohto setImageScaling:NSScaleToFit];
    [[self window]setTitle:[NSString stringWithFormat:NSLocalizedString(@"与%@的对话", nil) ,peerBuddy->buddyName]];
    if (bgImageName != @"NIL") {
        [chatMsg setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [sendMsg setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [self.window setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
    }
    else
    {
        [chatMsg setBackgroundColor:[NSColor  whiteColor]];
        [sendMsg setBackgroundColor:[NSColor  whiteColor]];
        [self.window setBackgroundColor:[NSColor  whiteColor]];
    }
}

-(void) changeBackgroundImage:(NSNotification*)notification
{
    NSString *bgImageName = [[notification userInfo] objectForKey:@"img"];//@"bg1";
    NSText *text = [self.window fieldEditor:YES forObject:self];
    if (bgImageName != @"NIL") {
        //取出背景图片
        [chatMsg setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [sendMsg setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [self.window setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [text setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
        [text setDrawsBackground:YES];
    }
    else
    {
        [chatMsg setBackgroundColor:[NSColor  whiteColor]];
        [sendMsg setBackgroundColor:[NSColor  whiteColor]];
        [self.window setBackgroundColor:[NSColor  whiteColor]];
        [text setBackgroundColor:[NSColor  whiteColor]];
        [text setDrawsBackground:YES];
    }
}

- (IBAction)send:(id)sender
{
    NSString *msg = [sendMsg stringValue];
    if (![msg isEqualToString:@""]) {
        if (peerBuddy.status == BUDDY_STATUS_ONLINE) {
            [pairChat sendMsg:msg];
            [self displayChatMessage:msg nameFlag:SELFNAME];
            [sendMsg setStringValue:@""];
        }
        else
        {
            [self displayChatMessage:NSLocalizedString(@"对方已离线",nil) nameFlag:SYSTEMNMAE];
            [sendMsg setStringValue:@""];
        }

    }
}

- (void) displayChatMessage:(NSString *)message nameFlag:(NSInteger)flag
{
    NSString * msg = [[NSString alloc]init];
    if (message != nil) {
        msg = [NSString stringWithFormat:@"%@\n", message];
        // 获取当前时间的字符串
        NSString *time = [[NSDate date] stringWithFormat:@"HH:mm:ss"];
        NSString *displayName = [[NSString alloc]init];
        switch (flag) {
            case 0:
                displayName = selfInfo.buddyName;
                break;
            case 1:
                displayName = peerBuddy.buddyName;
                break;
            case 2:
                displayName = NSLocalizedString(@"系统消息",nil);
                break;
                
            default:
                break;
        }
        
        NSString *title = [NSString stringWithFormat:@"%@:  %@\n",displayName,time];
        NSLog(@" >> %@", msg);
        
        chatMessage = [NSString stringWithFormat:@"%@%@%@", chatMessage,title, msg];
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        [chatMsg setString:chatMessage];
        NSRange range = [chatMessage rangeOfString:msg options:NSBackwardsSearch];
        [chatMsg scrollRangeToVisible:range];
    });
}

#pragma mark send file and show msg history

-(IBAction)sendFile:(id)sender
{
    /*选择文件发送*/
    BuddyGroup *firstBuddyGroup = [[[[MainWindowController sharedMainWindowController] buddySource] buddyGroupArray] objectAtIndex:0];
    for (NSInteger i=0; i<[firstBuddyGroup->buddyList count]; ++i)  // 遍历好友列表，找到发送上、下线提醒的好友
    {
        Buddy *buddy = [firstBuddyGroup->buddyList objectAtIndex:i];
        if (buddy->buddyQQ == peerBuddy->buddyQQ)
        {
            peerBuddy =  buddy;
            break;
        }
    }
    if (peerBuddy ->status == BUDDY_STATUS_OFFLINE) {
        [self showError:[[NSString alloc] initWithFormat:@"好友%@不在线",peerBuddy.buddyName]];
        return;
    }
    NSOpenPanel* openPanel = [NSOpenPanel openPanel];
	[openPanel setAllowsMultipleSelection:NO];
	[openPanel setMessage:NSLocalizedString(@"浏览文件:",nil)];
    [openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) 
     {  
         if (result == NSOKButton)
         {
             if ([[openPanel URL] isFileURL])
             {
                 [self sendFileInfo:[openPanel URL]];
             }
         }
     }];
}

- (void) sendFileInfo :(NSURL *) fileUrl
{
    NSFileManager * filemanager = [[NSFileManager alloc] init];
    BOOL isDirectory = NO;
    NSNumber *theFileSize;
    if([filemanager fileExistsAtPath:[fileUrl path] isDirectory:&isDirectory]){
        NSDictionary * attributes = [filemanager attributesOfItemAtPath:[fileUrl path] error:nil];
        theFileSize = [attributes objectForKey:NSFileSize];
        if (theFileSize == nil && [theFileSize doubleValue] <= 0)
        {
            [self showError:@"文件为空"];
            return;
        }
    }
    FileEntity *entity = [[FileEntity alloc] initWithFilePath:fileUrl sender:selfInfo receiver:peerBuddy fileSize:[theFileSize integerValue]];
    FileTransfer *transfer = [[FileTransfer alloc] initWithEntity:entity];
    [transfer sendFileInfo:peerBuddy];
  }

//查看历史聊天记录
- (IBAction)viewMsgHistory:(id)sender
{
    if (((MainWindowController*)[MainWindowController sharedMainWindowController]).msgWindowController == nil) {
        ((MainWindowController*)[MainWindowController sharedMainWindowController]).msgWindowController = [[MsgHistoryWindowController alloc] initWithWindowNibName:@"MsgHistoryWindowController"];
    }
    [((MainWindowController*)[MainWindowController sharedMainWindowController]).msgWindowController showWindow:nil];
    [((MainWindowController*)[MainWindowController sharedMainWindowController]).msgWindowController initContact:peerBuddy];
}

#pragma mark show alertview

-(void)showError:(NSString *)infoText
{
    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:NSLocalizedString(@"确定", nil)];
    [alert setMessageText:NSLocalizedString(@"连接失败",nil)];
    [alert setInformativeText:NSLocalizedString(infoText, nil)];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert beginSheetModalForWindow:[NSApp mainWindow] modalDelegate:self didEndSelector:@selector(sheetClosed:returnCode:contextInfo:) contextInfo:nil];
}

-(void)sheetClosed:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
    if (returnCode == NSAlertDefaultReturn) {
        [(__bridge_transfer NSWindow *)contextInfo close];
    }
}



@end
